package com.dotstone.chipism.activity;

import java.text.DecimalFormat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.MySocket.RecDataCallBackListener_Serach;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.OnDeviceStatusListener;
import com.dotstone.chipism.ui.timing.RemoteSocketTimingActivity;
import com.dotstone.chipism.ui.timing.util.AddSocketTimingManager;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class RemoteSocketActivity extends BaseActivity {

	private DecimalFormat dc = new DecimalFormat("0.000");

	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mPowerB;
	private TextView mTitleTv;
	private boolean power = false;
	private String address;
	private MySocket socket;
	private String id;
	private Device device;
	private boolean stop = false;
	private byte[] dianliudata;
	private byte[] dianyadata;
	private byte[] gonglvdata;
	private byte[] dianliangdata;
	private byte[] deviceAdd;
	private byte[] cmdData;
	private byte[] data2;
	private int[] dataCmd;
	private String gonglvCmd;
	private String dianyaCmd;
	private String dianliuCmd;
	private String dianliangCmd;
	private int data[] = new int[11];
	private byte buffer[] = new byte[11];
	 private String dianliangValue = "";
	private String dianliuValue = "";
	private String dianyaValue = "";
	private String gonglvValue = "";
	private TextView dianliu_tv;
	private TextView dianya_tv;
	private TextView gonglv_tv;
	private TextView dianliang_tv;
	private Button jiliang_btn;
	private Button dingshi_btn;
	private SVProgressHUD mSVProgressHUD;
	private int times = 0;
	private View bg;
	private LinearLayout jiliang_layout;
	private boolean received = false;
	// private byte[] deviceAdd;
	// private byte[] data = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
	// (byte) 0x82, (byte) 0x00, 0x00, 0x00 };
	@SuppressLint("NewApi")
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.power_b:
			if (power) { // 当前打开 发送关指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
				bg.setBackgroundResource(R.drawable.chazuo2x);
				sendCmd(device.getCloseCmd());
			} else { // 当前关闭 发送开的指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
				bg.setBackgroundResource(R.drawable.chaz2x);
				sendCmd(device.getOpenCmd());
			}
			power = !power;
			DeviceManager.getInstance().setDeviceState(id, power);
			break;
		case R.id.dingshi:
			startActivity(RemoteSocketTimingActivity.class);
//			ToastShow.Show(getApplicationContext(), "尚未完善");
			break;
		case R.id.jiliang:
			jiliang_btn.setClickable(false);
			dianliuValue = "";
			dianliangValue="";
			gonglvValue="";
			dianyaValue="";
			times = 0;
			check();
			mHandler.sendEmptyMessageDelayed(2, 10 * 1000);
			jiliang_layout.setAlpha(0f);
			jiliang_layout.setVisibility(View.VISIBLE);
			jiliang_layout.animate().alpha(1f).setDuration(2000).setListener(null);
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					mHandler.sendEmptyMessage(3);
				}
			}, 5000);
			break;
		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_socket;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mSVProgressHUD = new SVProgressHUD(RemoteSocketActivity.this);
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mPowerB = $(R.id.power_b);
		dianya_tv = $(R.id.dianya_tv);
		dianliu_tv = $(R.id.dianliu_tv);
		gonglv_tv = $(R.id.gonglv_tv);
		dingshi_btn = $(R.id.dingshi);
		dianliang_tv = $(R.id.dianliang_tv);
		jiliang_btn = $(R.id.jiliang);
		jiliang_layout = $(R.id.jiliang_layout);
		bg = $(R.id.bg);
		jiliang_btn.setOnClickListener(this);
		dingshi_btn.setOnClickListener(this);
		boolVersion();
		mTitleTv.setText("插座");
		mBackL.setOnClickListener(this);
		mPowerB.setOnClickListener(this);
		address = getIntent().getStringExtra("address");
		Log.i("wmy", "address = " + address);
		id = getIntent().getStringExtra("id");
		AddSocketTimingManager.getInstance().setId(id);
		device = DeviceManager.getInstance().getDeviceById(id);
		mTitleTv.setText("插座：" + device.getDeviceName());
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "没有找到所绑定网关，无法控制该设备!");
			finish();
		}
//		mSVProgressHUD.showWithStatus("正在获取设备状态");
		getDianliuCmd();
		checkStatus();
		power = DeviceManager.getInstance().checkDeviceState(id);
		if (power) {
			mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
			bg.setBackgroundResource(R.drawable.chaz2x);
		} else {
			mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
			bg.setBackgroundResource(R.drawable.chazuo2x);
		}
		setListener();
	}

	public void checkStatus() {
		mSVProgressHUD.showWithStatus("正在获取设备状态");
		check();
		socket.setRecDataCallBackListener_Serach(new RecDataCallBackListener_Serach() {

			@Override
			public void onReceiveData(String data) {
				// TODO Auto-generated method stub
				Log.e("wmy", "164 从mysocket获取插座状态");
				received = true;
				parseRecData(data);

			}
		});
		SocketManager.getInstance().setOnDeviceStatusListener(new OnDeviceStatusListener() {

			@Override
			public void onStatus(String data, int what) {
				// TODO Auto-generated method stub
				// mHandler.sendEmptyMessage(what);
				Log.e("wmy", "175插座收到返回数据" + data);
				received = true;
				parseRecData1(data);
			}
		});
		checkTimeout();
	}


	@Override
	protected void onStop() {
		super.onStop();
		if (isFinishing()){
			AddSocketTimingManager.close();
		}
	}

	private void checkTimeout(){
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(!received){
					mHandler.sendEmptyMessage(4);
				}
			}
		}, 10*1000);
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				 if (mSVProgressHUD.isShowing()) {
				 mSVProgressHUD.dismiss();
				 }

				mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
				bg.setBackgroundResource(R.drawable.chaz2x);
				power = true;
				break;
			case 1:
				 if (mSVProgressHUD.isShowing()) {
				 mSVProgressHUD.dismiss();
				 }
				mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
				bg.setBackgroundResource(R.drawable.chazuo2x);
				power = false;
				break;
			case 2:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				break;
			case 3:
				jiliang_layout.animate().alpha(0f).setDuration(2000).setListener(new AnimatorListener() {

					@Override
					public void onAnimationEnd(Animator animation) {
						// TODO Auto-generated method stub
						jiliang_layout.setVisibility(View.GONE);
						jiliang_btn.setClickable(true);
					}

					@Override
					public void onAnimationStart(Animator animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationCancel(Animator animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationRepeat(Animator animation) {
						// TODO Auto-generated method stub

					}

				});
				break;
			case 4:
				if (mSVProgressHUD.isShowing()) {
					mSVProgressHUD.dismiss();
				}
				ToastShow.Show(getApplicationContext(), "获取状态失败：连接超时或设备未通电");
				break;
			default:
				break;
			}
		}
	};

	private void parseRecData(String data) {
	
		if (data.length() < 10 || data == null) {
			return;
		}
		JSONObject jo;
		// Log.i("wmy", "获取插座状态" + data);
		try {
			jo = new JSONObject(data);
			String a = jo.getString("a");
			if (a.equals("20000")) {
				int msgId = jo.getInt("b");
				String g = jo.getString("g");
				JSONObject jo1 = new JSONObject(g);
				JSONArray jsonArray = jo1.optJSONArray("data");
				int dataja[] = new int[jsonArray.length()];
				if (jsonArray != null) {
					for (int i = 0; i < jsonArray.length(); i++) {
						dataja[i] = (Integer) jsonArray.get(i);
					}
					if (dataja.length == 8) {
						if (dataja[(jsonArray.length() - 1)] == 121) {
							DeviceManager.getInstance().setDeviceState(msgId + "", true);
							mHandler.sendEmptyMessage(0);
						} else if (dataja[(jsonArray.length() - 1)] == 120) {
							DeviceManager.getInstance().setDeviceState(msgId + "", false);
							mHandler.sendEmptyMessage(1);
						} else if (dataja[(jsonArray.length() - 1)] == 255) {
							DeviceManager.getInstance().setDeviceState(msgId + "", true);
							mHandler.sendEmptyMessage(0);
						} else if (dataja[(jsonArray.length() - 1)] == 0) {
							DeviceManager.getInstance().setDeviceState(msgId + "", false);
							mHandler.sendEmptyMessage(1);
						}
					} else if (dataja.length == 11) {
						if (dataja[7] == 255) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为开");
							DeviceManager.getInstance().setDeviceState(msgId + "", true);
							mHandler.sendEmptyMessage(0);
						} else if (dataja[7] == 0) {
							// Log.i("wmy", "获取ID为" + msgId + "的设备的状态为关");
							DeviceManager.getInstance().setDeviceState(msgId + "", false);
							mHandler.sendEmptyMessage(1);
						}
					}
				}
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	private void parseRecData1(String recData) {
		try {
			JSONObject jsonObject = new JSONObject(recData);
			String gString = jsonObject.getString("g");
			JSONObject g = new JSONObject(gString);
			JSONArray dataArray = g.getJSONArray("data");
			for (int i = 0; i < dataArray.length(); i++) {
				data[i] = (Integer) dataArray.get(i);
			}
			for (int i = 0; i < data.length; i++) {
				buffer[i] = (byte) data[i];
			}
			byte[] temp = new byte[5];
			System.arraycopy(buffer, 1, temp, 0, 5);
			String add = Util.bytesToHexString(temp).toUpperCase();
			if (buffer.length == 12) {

			}
			if (!device.getDeviceAddress().equals(add)) {
				// Log.d("wmy", "和当前测试的不一样");
				return;
			} else {
				// Log.i("wmy", "和当前测试的一样");
				if (buffer[6] == 18) {
					int time1 = (int) (buffer[8] & 0x000000ff);
					int time2 = (int) ((buffer[10] << 8) & 0x0000ff00);
					int time3 = (int) ((buffer[11] << 16) & 0x00ff0000);
					final int time = time1 + time2 + time3;
				} else if (buffer[6] == 17) {
					Log.e("qjx", "343功率返回 = " + recData);
					String str = Integer.toHexString((int) (buffer[7] & 0xFF));// 开关
					// Log.e("mqtt", "341开关返回 = " + (int) (buffer[7] & 0xFF));
					if ((int) (buffer[7] & 0xFF) == 255) {
						mHandler.sendEmptyMessage(0);
						DeviceManager.getInstance().setDeviceState(id, true);
					} else if ((int) (buffer[7] & 0xFF) == 0) {
						mHandler.sendEmptyMessage(1);
						DeviceManager.getInstance().setDeviceState(id, false);
					}
					String strdata = Integer.toHexString((int) (buffer[8] & 0xFF));
					int data1 = Integer.valueOf(strdata, 16);
					// Log.e("wmy", "347功率返回 = " + strdata + " " + data1);
					strdata = Integer.toHexString((int) (buffer[9] & 0xFF));
					int data2 = Integer.valueOf(strdata, 16);
					strdata = Integer.toHexString((int) (buffer[10] & 0xFF));
					int data3 = Integer.valueOf(strdata, 16);
					int mode = (data3 >>> 7) & 0x01;
					// Log.e("wmy", "353功率返回 data2 = " + data2 + " " + "");
					float number = ((data3 & 0xff) << 16) | ((data2 & 0xff) << 8) | data1;
					// Log.e("wmy", "355功率返回 number = " + number);
					float pw = 0.0f;
					if (mode == 0) {// 正向功率
						pw = number / 110.2151f;
						// Log.e("wmy", "正向功率"+pw);
					} else if (mode == 1) {// 负向功率
						number = (float) (Math.pow(2, 24) - number);
						pw = number / 110.2151f;
						// Log.e("wmy", "负向功率"+pw);
					}
					gonglvValue = dc.format(pw);
					// Log.e("wmy", "365功率"+pw);
				} else if (buffer[6] == 19) {
					// 电压
					Log.e("qjx", "325电压返回 = " + recData);
					int v2 = 0xff & (buffer[8]);
					int v3 = 0xff00 & (buffer[9] << 8);
					int v4 = 0xff0000 & (buffer[10] << 16);
					double dianya = (float) (v2 + v3 + v4) / 10581.085;
					dianyaValue = dc.format(dianya);
					// Log.i("wmy", "获取电压 = " + dianyaValue);
				} else if (buffer[6] == 20) {
					// 电流
					Log.e("qjx", "334电流返回 = " + recData);
					int v2 = 0xff & (buffer[8]);
					int v3 = 0xff00 & (buffer[9] << 8);
					int v4 = 0xff0000 & (buffer[10] << 16);
					String value_dianliu;
					double dianliu = ((float) (v2 + v3 + v4)) / 93113.5488;
					dianliuValue = dc.format(dianliu);
					// Log.i("wmy", "获取电流 = " + dianliuValue);
				} else if (buffer[6] == 22) {
					// 电量
					Log.e("qjx", "415电量返回 = " + recData);
					int v1 = 0xff & buffer[7];
					int v2 = 0xff00 & (buffer[8] << 8);
					int v3 = 0xff0000 & (buffer[9] << 16);
					int v4 = 0xff000000 & (buffer[10] << 24);
					int value = v1 + v2 + v3 + v4;
					double dianliang = (float) value / 3700;
					dianliangValue = dc.format(dianliang);
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				dianya_tv.setText(dianyaValue + "V");
				dianliu_tv.setText(dianliuValue + "A");
				gonglv_tv.setText(gonglvValue + "W");
				dianliang_tv.setText( dianliangValue+ "Kw/h");
				if (!dianyaValue.equals("") && !dianliuValue.equals("") && !gonglvValue.equals("")) {
					if (mSVProgressHUD.isShowing()) {
						mSVProgressHUD.dismiss();
					}
				}
			}
		});
	}

	private void getDianliuCmd() {
		gonglvdata = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x11, (byte) 0x00, 0x00, 0x00 };
		dianliudata = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x14, (byte) 0x00, 0x00, 0x00 };
		dianyadata = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x13, (byte) 0x00, 0x00, 0x00 };
		dianliangdata = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x16, (byte) 0x00, 0x00, 0x00 };
		data2 = getCmdData(gonglvdata, device.getDeviceAddress());
		dataCmd = byte2HexStr(data2);
		gonglvCmd = transCmd(dataCmd);
		Log.e("wmy", "功率 = " + gonglvCmd);

		data2 = getCmdData(dianliudata, device.getDeviceAddress());
		dataCmd = byte2HexStr(data2);
		dianliuCmd = transCmd(dataCmd);

		data2 = getCmdData(dianyadata, device.getDeviceAddress());
		dataCmd = byte2HexStr(data2);
		dianyaCmd = transCmd(dataCmd);
		
		data2 = getCmdData(dianliangdata, device.getDeviceAddress());
		dataCmd = byte2HexStr(data2);
		dianliangCmd = transCmd(dataCmd);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		check();
//		mHandler.sendEmptyMessageDelayed(2, 10 * 1000);
	}

	private void check() {
		times++;
		int count = 0;
		if (times >= 3) {
			return;
		}
		if (dianliuValue.equals("")) {
			count++;
			socket.sendMqttDataDelay(dianliuCmd);
		}
		if (dianyaValue.equals("")) {
			count++;
			socket.sendMqttDataDelay(dianyaCmd);
		}
		if (gonglvValue.equals("")) {
			count++;
			socket.sendMqttDataDelay(gonglvCmd);
		}
		if(dianliangValue.equals("")){
			count++;
			socket.sendMqttDataDelay(dianliangCmd);
		}
		Log.i("wmy", "count = "+count);
		if (count != 0) {
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					check();
				}
			}, count * 1000);
		} else {
			mHandler.sendEmptyMessage(2);
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		stop = true;
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub
		socket.setRecDataCallBackListener_Serach(new RecDataCallBackListener_Serach() {

			@Override
			public void onReceiveData(String recData) {
				// TODO Auto-generated method stub
				// Log.e("wmy", "获取 = " + recData);
				parseRecData1(recData);
				// byte [] dataByte = Util.hexStringToBytes(data);
			}
		});

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	private void sendCmd(String cmd) {
		Log.i("onResponse" , "cmd:" + cmd);
		if (socket.isLocalSuccess()) {
			socket.sendMqttData(cmd);
		} else {
			SocketManager.getInstance().sendRemoteData(socket.getMac(), device.getMainDeviceId(), cmd);
		}
	}

	private byte[] getCmdData(byte[] commandData, String deviceAddress) {
		int CMDLENGTH = 10;
		deviceAdd = hexStringToBytes(deviceAddress);
		cmdData = new byte[CMDLENGTH];
		System.arraycopy(commandData, 0, cmdData, 0, CMDLENGTH);
		System.arraycopy(deviceAdd, 0, cmdData, 1, 5);
		return cmdData;
	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	public static int[] byte2HexStr(byte[] b) {
		int[] cmd = new int[b.length];
		String stmp = "";
		StringBuilder sb = new StringBuilder("");
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			sb.append((stmp.length() == 1) ? stmp : stmp);
			sb.append(",");
			cmd[n] = Integer.parseInt(stmp, 16);
		}
		return cmd;
	}

	private String transCmd(int data[]) {
		String sendStr = "";
		JSONObject jo = new JSONObject();
		JSONObject jo1 = new JSONObject();
		try {
			jo.put("a", "20000");
			jo.put("b", Integer.parseInt(id));
			jo.put("c", "20," + SocketManager.getInstance().user_id);
			jo.put("d", "10," + DeviceManager.getInstance().getmWlanId());
			jo.put("e", 1);
			jo.put("f", System.currentTimeMillis());
			jo.put("h", "0.0.1");
			jo1.put("cmd", 100);
			if (data != null && data.length != 0) {
				JSONArray ja = new JSONArray();
				for (int i = 0; i < data.length; i++) { // 依次将数组元素添加进JSONArray对象中
					ja.put(data[i]);
				}
				jo1.put("data", ja);
			}
			jo.put("g", "" + jo1 + "");
			sendStr = jo.toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sendStr;
	}

}
